import { defineStore } from 'pinia'
import { useQuery, useMutation } from '@tanstack/vue-query'
import api from '../api'

export const useFamilyStore = defineStore('family', {
  state: () => ({
    members: [],
    selectedFamilyTree: null
  }),
  
  getters: {
    getMembers: (state) => state.members,
    getSelectedFamilyTree: (state) => state.selectedFamilyTree
  },
  
  actions: {
    setMembers(members) {
      this.members = members
    },
    
    setSelectedFamilyTree(treeId) {
      this.selectedFamilyTree = treeId
    },
    
    // 获取成员列表的 useQuery 配置
    useFetchMembers() {
      return useQuery({
        queryKey: ['family-members'],
        queryFn: () => api.get('/members'),
        onSuccess: (result) => {
          this.members = result.data.data || []
        },
        onError: (error) => {
          console.error('获取成员列表失败:', error)
        }
      })
    },
    
    // 创建成员的 useMutation 配置
    useCreateMember() {
      return useMutation({
        mutationFn: (memberData) => api.post('/members', memberData),
        onError: (error) => {
          console.error('创建成员失败:', error)
        }
      })
    },
    
    // 更新成员的 useMutation 配置
    useUpdateMember() {
      return useMutation({
        mutationFn: ({ id, data }) => api.put(`/members/${id}`, data),
        onError: (error) => {
          console.error('更新成员失败:', error)
        }
      })
    },
    
    // 删除成员的 useMutation 配置
    useDeleteMember() {
      return useMutation({
        mutationFn: (id) => api.delete(`/members/${id}`),
        onError: (error) => {
          console.error('删除成员失败:', error)
        }
      })
    },
    
    // 刷新成员列表
    async refreshMembers() {
      // 这个方法将在组件中通过 invalidateQueries 实现
    },
    
    // 根据家族树获取成员的 useQuery 配置
    useFetchMembersByFamilyTree() {
      return useQuery({
        queryKey: ['family-members', this.selectedFamilyTree],
        queryFn: () => {
          if (!this.selectedFamilyTree) {
            return Promise.resolve({ data: { data: [] } });
          }
          return api.get(`/members/family-tree/${this.selectedFamilyTree}`)
        },
        enabled: !!this.selectedFamilyTree,
        onSuccess: (result) => {
          this.members = result.data.data || []
        },
        onError: (error) => {
          console.error('获取家族树成员失败:', error)
        }
      })
    }
  }
})